<template>
    <el-card>
        <div class="chatContent" v-if="textList.length" ref="chatRef">
            <div v-for="(item, index) in textList" :key="index" class="text-item"
                :class="item.position === 'right' ? 'text-item-right' : ''">
                <template v-if="item.position === 'left'">
                    <div class="chat-name"
                        style="background: linear-gradient(to bottom right, #ff7e5f, #feb47b, #6dd5ed, #ff758e);">
                        {{ item.name }}</div>
                    <el-icon class="is-loading" style="margin-left: 12px;"
                        v-if="!item.content && item.contentType === '0'" color="black">
                        <Loading />
                    </el-icon>
                    <div class="chat-box" v-html="md.render(item.content)" v-if="item.contentType === '0'">
                    </div>
                    <div class="leftImg" @click="downloadImg(item.content)" v-if="item.contentType === '1'">
                        <el-image :src="item.content ? url + item.content : ''" fit="fill">
                            <template #error>
                                <el-icon class="is-loading" color="black">
                                    <Loading />
                                </el-icon>
                            </template>
                        </el-image>
                    </div>
                </template>
                <template v-else>
                    <div class="chat-box" v-if="item.contentType === '0'">{{ item.content }}</div>
                    <div class="rightImg" @click="downloadImg(item.content)" v-if="item.contentType === '1'">
                        <el-image :src="item.content ? url + item.content : ''" fit="fill">
                            <template #error>
                                <el-icon class="is-loading" color="black">
                                    <Loading />
                                </el-icon>
                            </template>
                        </el-image>
                    </div>
                    <div class="chat-name" style="background:linear-gradient(to right, #ff7e5f, #feb47b);">
                        {{ item.name }}
                    </div>
                </template>
            </div>
        </div>
        <el-divider v-if="textList.length" />
        <div class="inputContent">
            <div class="input">
                <textarea :placeholder="inputDisabled ? 'blue正在绞尽脑汁思考问题，请稍等一下~' : '尽管问...'" v-model="message"
                    :disabled="inputDisabled" @keyup.enter="sendMessage"></textarea>
            </div>
            <div class="uploadImg" v-if="code">
                <el-image :src="url + code" fit="fill">
                    <template #error>
                        <el-icon class="is-loading" color="black">
                            <Loading />
                        </el-icon>
                    </template>
                </el-image>
                <el-icon @click="code = ''">
                    <Close />
                </el-icon>
            </div>
            <div class="bar">
                <div class="left" v-if="!inputDisabled">
                    <el-switch v-model="isContext" @change="changeContext" />
                    <span>开启记忆功能</span>
                </div>
                <div class="right" v-if="!inputDisabled">
                    <el-tooltip content="语音输入" v-if="isSupport">
                        <div class="option" @touchstart="startRecord" @touchend="endRecord">
                            <el-icon size="25">
                                <Microphone />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip content="不支持语音输入" v-else>
                        <div class="option">
                            <el-icon size="25">
                                <Mute />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip content="上传图片">
                        <div class="option">
                            <input id="fileInput" type="file" style="display:none;" @change="handleFileChange" />
                            <el-icon size="25" @click="selectFile">
                                <Upload />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip content="保存会话">
                        <div class="option" @click="saveChat">
                            <el-icon size="25">
                                <Finished />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip content="发送">
                        <div class="option" @click="sendMessage">
                            <el-icon size="25">
                                <Position />
                            </el-icon>
                        </div>
                    </el-tooltip>
                </div>
            </div>
        </div>
        <div class="sound-sonic_wave" v-if="isRecording">
            <div class="wave w1"></div>
            <div class="wave w2"></div>
        </div>
    </el-card>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { Position, Finished, Loading, Upload, Close, Microphone, Mute } from '@element-plus/icons-vue'
import { fetchEventSource } from "@microsoft/fetch-event-source";
import api from '@/api'
import { Decrypt } from '@/utils/secret.js'
import VueEvent from '@/utils/event.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import formatterDate from '@/utils/date';
import { guid } from '@/utils/busi';
import { md } from '@/utils/md';
import { debounce } from '@/utils/busi';
import { isMobile } from '@/utils/busi';

const props = defineProps({
    token: String,
    username: String
})
const message = ref()//发送的消息
const textList = ref([])//消息列表
const emit = defineEmits(['sendData']);
const showLogo = ref(true)//是否展示logo
const inputDisabled = ref(false)//是否允许输入
const isContext = ref(false)//是否开启记忆功能
const code = ref('')//上传图片的编码
const recognition = ref(null);//语音录入
const isRecording = ref(false)//是否正则语音录入
const isSupport = ref(false)//是否支持语音录音
const url = ref(import.meta.env.VITE_BASE_URL + '/system/file/download/')//图片下载地址

//contentType内容类型0-文字,1-图片
const sendMessage = async () => {
    const date = formatterDate(new Date)
    const msg = message.value
    message.value = null
    //隐藏logo
    if (showLogo.value) {
        showLogo.value = false
        emit('sendData', false)
    }
    if (msg && msg.trim() !== '') {
        textList.value.push({ name: props.username ? props.username : '游客', content: msg, position: 'right', contentType: '0', contentTime: date })
        if (props.token) {
            //订阅校验
            const contextId = sessionStorage.getItem('contextId')
            const param = {
                content: msg,
                contentTime: date,
                imgCode: code.value,
                contextId: contextId
            }
            const res = await api.post('/ai/userSubscribe/checkSubscribe', param)
            if (res.data.code !== 200) {
                textList.value.push({ name: 'blue', content: res.data.msg, position: 'left', contentType: '0', contentTime: date })
                return
            }
            //上传了图片调用图标分析
            if (code.value) {
                textList.value.push({ name: props.username, content: code.value, position: 'right', contentType: '1', contentTime: date })
                textList.value.push({ name: 'blue', content: '', position: 'left', contentType: '0', contentTime: date })
                chat(msg, null, code.value)
                code.value = ''
            } else if (msg.includes('生成') && msg.includes('图片')) {
                //如果对话中存在生成图片关键字调用文生图接口
                textList.value.push({ name: 'blue', content: 'blue正在加班加点为你生成图片，请耐心等待哟~', position: 'left', contentType: '0', contentTime: date })
                textList.value.push({ name: 'blue', content: '', position: 'left', contentType: '1', contentTime: date })
                texToImg(msg)
            } else {
                textList.value.push({ name: 'blue', content: '', position: 'left', contentType: '0', contentTime: date })
                if (isContext.value && contextId) {
                    chat(msg, contextId, null)
                } else {
                    chat(msg, null, null)
                }
            }
        } else {
            //未登录提示登录
            textList.value.push({ name: 'blue', content: '您还未登录哟,登录菜单栏如未显示可轻触左侧边缘切换菜单栏状态~', position: 'left', contentType: '0', contentTime: date })
        }
    } else {
        textList.value.push({ name: 'blue', content: '你想对blue说点什么呢?', position: 'left', contentType: '0', contentTime: date })
    }
}

const chat = async (message, contextId, code) => {
    inputDisabled.value = true
    //匹配英文单词结尾正则
    const regex1 = /[a-zA-Z]$/
    //匹配首字母大写尾字母小写正则
    const regex2 = /^[A-Z][a-zA-Z]*[a-z]$/
    let url
    const param = { 'message': message }
    if (code) {
        url = import.meta.env.VITE_BASE_URL + '/ai/openAi/multiChat'
        param['code'] = code
    } else if (contextId) {
        url = import.meta.env.VITE_BASE_URL + '/ai/openAi/streamContextChat'
        param['contextId'] = contextId
    } else {
        url = import.meta.env.VITE_BASE_URL + '/ai/openAi/streamChat'
    }
    const ctrl = new AbortController()
    let text = ''
    await fetchEventSource(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'token': Decrypt(props.token),
            'accessAuthor': 'allow'
        },
        body: JSON.stringify(param),
        signal: ctrl.signal,
        onmessage: (message) => {
            let msg = message.data
            if (regex1.test(message.data)) {
                msg = msg + ' '
                if (regex2.test(message.data) && text.slice(-1) === ' ') {
                    text = text.slice(0, -1);
                }
            }
            text = text + msg
            textList.value[textList.value.length - 1].content = text
        },
        onclose() {
            inputDisabled.value = false
            ctrl.abort()
        },
        onerror(err) {
            textList.value[textList.value.length - 1].content = 'blue出错了，请稍后再试下吧~'
            inputDisabled.value = false
            throw err
        }
    });
}
const texToImg = async (message) => {
    inputDisabled.value = true
    const res = await api.post('/ai/openAi/textToImg', { message: message })
    if (res.data.code === 200) {
        textList.value[textList.value.length - 1].content = res.data.data
        textList.value.push({ name: 'blue', content: '图片生成已完成，点击图片可进行下载哟~', position: 'left', contentType: '0', contentTime: formatterDate(new Date) })
    } else {
        textList.value[textList.value.length - 1].content = 'blue出错了，请稍后再试下吧~'
    }
    inputDisabled.value = false
}
const clearMessage = () => {
    textList.value = []
    message.value = null
    showLogo.value = true
    emit('sendData', true)
}
const saveChat = () => {
    if (!props.token) {
        showLogo.value = false
        emit('sendData', false)
        textList.value.push({ name: 'blue', content: '您还未登录哟,登录菜单栏如未显示可轻触左侧边缘切换菜单栏状态~', position: 'left', contentType: '0', contentTime: formatterDate(new Date) })
        return
    }
    if (textList.value.length === 0) {
        showLogo.value = false
        emit('sendData', false)
        textList.value.push({ name: 'blue', content: '先聊点什么吧~', position: 'left', contentType: '0', contentTime: formatterDate(new Date) })
        return
    }
    ElMessageBox.prompt('请输入会话名称', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPattern: /^.{0,10}$/,
        inputErrorMessage: '名称最多10位'
    }).then(async ({ value }) => {
        const param = {
            sessionNm: value,
            chatHistoryDetailDTOS: textList.value
        }
        const res = await api.post('/ai/chatHistory/add', param)
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
            VueEvent.emit("hisChatList")
        } else {
            ElMessage.error(res.data.msg)
        }
    }).catch(() => { })
}

const downloadImg = debounce(async (code) => {
    const res = await api.get('/system/file/download/' + code, null, "blob")
    let data = res.data
    const blob = new Blob([data], {
        type: 'image/png;charset=UTF-8'
    })
    let url = URL.createObjectURL(blob)
    let a = document.createElement('a')
    a.href = url
    a.download = 'ai图片.png'
    a.click()
    //下载完成后清理URL对象和a标签
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
}, 1000)

const changeContext = (value) => {
    if (value) {
        sessionStorage.setItem('contextId', guid())
    } else {
        sessionStorage.removeItem('contextId')
    }
}
//滚动条自动滚动到底部
const chatRef = ref();
watch(textList, () => {
    nextTick(() => {
        if (!showLogo.value) {
            const content = chatRef.value;
            content.scrollTo({ top: content.scrollHeight });
        }
    });
}, {
    deep: true,
})

const showHisChat = async (historyId) => {
    const res = await api.get('/ai/chatHistoryDetail/list', { historyId: historyId })
    if (res.data.code === 200) {
        showLogo.value = false
        emit('sendData', false)
        textList.value = res.data.data
    } else {
        ElMessage.error(res.data.msg)
    }
}

const selectFile = () => {
    if (code.value) {
        const text = { name: 'blue', content: '只支持单张图片分析哟~', position: 'left', contentType: '0', contentTime: formatterDate(new Date) }
        textList.value.push(text)
        if (showLogo.value) {
            showLogo.value = false
            emit('sendData', false)
        }
        return
    }
    document.getElementById('fileInput').click();
}

const handleFileChange = async () => {
    const file = fileInput.files[0]
    const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
    if (!isJPG) {
        textList.value.push({ name: 'blue', content: '请上传png或jpg格式图片', position: 'left', contentType: '0', contentTime: formatterDate(new Date) })
        if (showLogo.value) {
            showLogo.value = false
            emit('sendData', false)
        }
        return
    }
    const formData = new FormData();
    formData.append('file', file);
    const res = await api.post('/system/file/upload?business=ai多模态', formData)
    if (res.data.code == 200) {
        code.value = res.data.data
    } else {
        textList.value.push({ name: 'blue', content: '图片上传失败，失败原因：' + res.data.msg, position: 'left', contentType: '0', contentTime: formatterDate(new Date) })
        if (showLogo.value) {
            showLogo.value = false
            emit('sendData', false)
        }
    }

}

const startRecord = () => {
    isRecording.value = true
    if (!recognition.value) {
        recognition.value = new webkitSpeechRecognition() || new SpeechRecognition();
        recognition.value.lang = 'cmn-Hans-CN';//设置识别语言
        recognition.value.continuous = true;//是否连续识别
        recognition.value.onresult = handleRecognitionResults;//结果返回函数
    }
    recognition.value.start();
}

const endRecord = () => {
    if (recognition.value) {
        recognition.value.stop();
        isRecording.value = false
    }
}

const handleRecognitionResults = (event) => {
    const transcript = event.results[0][0].transcript;
    message.value = transcript;
}

onMounted(() => {
    VueEvent.on("hotKey", (data) => {
        if (!inputDisabled.value) {
            message.value = data
            sendMessage()
        }
    })
    VueEvent.on("historyId", (data) => {
        showHisChat(data)
    })
    VueEvent.on("clearMessage", () => {
        clearMessage()
    })
    //判断是否支持语音输入
    if (('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) && isMobile()) {
        isSupport.value = true
    }
})
onUnmounted(() => {
    if (recognition.value) {
        recognition.value.stop();
    }
    recognition.value = null
})
</script>
<style scoped lang="less">
textarea {
    width: 100%;
    min-height: 80px;
    border: none;
    outline: none;
    resize: none;
    font-size: 16px;
}

.bar {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: space-between;

    .left {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        font-size: 12px;
        color: #ABB2B9;
    }

    .right {
        display: flex;
        justify-content: right;

        .option {
            height: 40px;
            width: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            cursor: pointer;
        }

        .option:hover {
            background-color: #DCDCDC;
        }
    }
}

.chatContent {
    max-height: 50vh;
    overflow: auto;
}

@media screen and(max-width:1000px) {
    .chatContent {
        max-height: 65vh;
        height: 65vh;
    }
}

.chatContent::-webkit-scrollbar {
    display: none;
}

.text-item {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    color: #FFFFFF;

    &:last-child {
        margin-bottom: 0;
    }
}

.chat-name {
    width: 42px;
    height: 42px;
    text-align: center;
    line-height: 42px;
    font-size: 12px;
    font-weight: bold;
    border-radius: 50%;
    color: #Ffffff;
    flex-shrink: 0;
}

.chat-box {
    text-align: left;
    margin-left: 12px;
    padding: 0 8px;
    max-width: calc(100% - 70px);
    background: #2D65F7;
    position: relative;
    border-radius: 10px;
}

.leftImg {
    min-width: 100px;
    text-align: left;
    margin-left: 12px;
    display: flex;
    justify-content: left;
    align-items: center;
    gap: 10px;

    .el-image {
        border-radius: 10px;
        height: 60%;
        width: 60%;
    }
}

.rightImg {
    min-width: 100px;
    text-align: right;
    margin-right: 12px;
    display: flex;
    justify-content: right;
    align-items: center;
    gap: 10px;

    .el-image {
        border-radius: 10px;
        height: 60%;
        width: 60%;
    }
}

.typing {
    font-size: 14px;
}

.text-item-right {
    justify-content: flex-end;
}

.text-item-right .chat-box {
    margin-left: 0;
    margin-right: 15px;
    padding: 10px 8px;
}

.uploadImg {
    height: 80px;
    width: 80px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;

    .el-image {
        border-radius: 10px;
    }
}

.wave {
    position: absolute;
    top: calc((100% - 60px)/2);
    left: calc((100% - 60px)/2);
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-attachment: fixed;
    background-position: center center;
}

.w1 {
    z-index: 2;
    border: 1px solid #6dd5ed;
    background-size: auto 106%;
    animation: wave 1s infinite;
}

.w2 {
    z-index: 3;
    border: 1px solid #ff758e;
    animation: wave 1s .2s infinite;
}

@keyframes wave {
    0% {
        top: calc((100% - 60px)/2);
        left: calc((100% - 60px)/2);
        width: 60px;
        height: 60px;
    }

    100% {
        top: calc((100% - 120px)/2);
        left: calc((100% - 120px)/2);
        width: 120px;
        height: 120px;
        opacity: 0.4;
    }
}
</style>